package com.itjdo.springboot_mail_system.mail;

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class MailService {

	@Value("${spring.mail.username}")
	private String from;// 发送人邮箱

	@Value("${spring.mail.password}")
	private String mailPassword; // 发送人邮箱密码

	@Value("${spring.mail.host}")
	private String mailHost;

	@Async // 异步调用
	public void sengMail(String title, String text, String email) {
		try {
			Properties props = new Properties();
			props.put("userName", from);
			props.put("passWord", mailPassword);
			props.put("mail.smtp.timeout", "25000");
			props.put("mail.transport.protocol", "smtp");
			props.put("mail.smtp.host", mailHost);
			props.put("mail.smtp.port", "25");
			Session mailSession = Session.getDefaultInstance(props);
			Message msg = new MimeMessage(mailSession);
			msg.setFrom(new InternetAddress(from));
			msg.addRecipients(Message.RecipientType.CC, InternetAddress.parse(props.getProperty("userName")));
			msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
			msg.setSubject(title);
			msg.setText(text);
			msg.saveChanges();
			Transport transport = mailSession.getTransport("smtp");
			transport.connect(props.getProperty("mail.smtp.host"), props.getProperty("userName"), props.getProperty("passWord"));
			transport.sendMessage(msg, msg.getAllRecipients());
			transport.close();
		} catch (MessagingException e) {
			e.printStackTrace();
		}

	}
}
